<template>
    <div class="payment-result">
        <el-card>
            <template #header>
                <div class="card-header">
                    <span>支付结果</span>
                </div>
            </template>
            
            <div v-if="loading" class="loading-container">
                <el-skeleton :rows="3" animated />
            </div>
            
            <div v-else class="result-container">
                <!-- 状态处理中 -->
                <div v-if="isProcessing" class="processing-container">
                    <el-result
                        icon="info"
                        title="正在处理支付结果"
                        sub-title="系统正在处理您的支付，请稍候..."
                    >
                        <template #extra>
                            <div class="processing-indicator">
                                <el-progress type="circle" :percentage="processingProgress" status="warning" />
                            </div>
                        </template>
                    </el-result>
                </div>
                
                <!-- 最终状态 -->
                <div v-else>
                    <el-result
                        :icon="paymentSuccess ? 'success' : 'error'"
                        :title="paymentSuccess ? '支付成功' : '支付失败'"
                        :sub-title="paymentSuccess ? '您已成功支付家教费用' : '支付过程中发生错误'"
                    >
                        <template #extra>
                            <el-button type="primary" @click="goToSchedule">返回课程安排</el-button>
                            <el-button @click="goToPaymentRecords">查看支付记录</el-button>
                        </template>
                    </el-result>
                    
                    <div v-if="order" class="order-details">
                        <el-descriptions :column="1" border>
                            <el-descriptions-item label="订单编号">{{ order.orderNo }}</el-descriptions-item>
                            <el-descriptions-item label="课程名称">{{ order.tutoringTitle }}</el-descriptions-item>
                            <el-descriptions-item label="教师姓名">{{ order.teacherName }}</el-descriptions-item>
                            <el-descriptions-item label="支付金额">¥{{ order.amount }}</el-descriptions-item>
                            <el-descriptions-item label="支付状态">
                                <el-tag :type="getStatusType(order.status)">
                                    {{ getStatusText(order.status) }}
                                </el-tag>
                            </el-descriptions-item>
                            <el-descriptions-item label="创建时间">
                                {{ formatDateTime(order.createTime) }}
                            </el-descriptions-item>
                        </el-descriptions>
                    </div>
                </div>
            </div>
        </el-card>
    </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { paymentService } from '@/api/payment'
import { formatDateTime } from '@/utils/format'

const router = useRouter()
const route = useRoute()
const loading = ref(true)
const order = ref(null)
const paymentSuccess = ref(false)
const orderNo = ref(null)
const pollingTimer = ref(null)
const pollingCount = ref(0)
const MAX_POLLING_COUNT = 10
const POLLING_INTERVAL = 2000

// 支付处理中状态
const isProcessing = ref(true) // 默认显示处理中
const processingProgress = ref(0) // 处理进度

// 获取支付状态类型
const getStatusType = (status) => {
    switch (status) {
        case 0: return 'warning'  // 未支付
        case 1: return 'success'  // 支付成功
        case 2: return 'danger'   // 支付失败
        default: return 'info'
    }
}

// 获取支付状态文本
const getStatusText = (status) => {
    switch (status) {
        case 0: return '未支付'
        case 1: return '支付成功'
        case 2: return '支付失败'
        default: return '未知状态'
    }
}

// 跳转到课程安排页面
const goToSchedule = () => {
    router.push('/student/schedule')
}

// 跳转到支付记录页面
const goToPaymentRecords = () => {
    router.push('/payment/records')
}

// 检查支付结果
const checkPaymentResult = async (isPolling = false) => {
    if (!isPolling) {
        loading.value = true
    }
    
    // 如果已经有订单号，直接使用
    if (!orderNo.value) {
        // 获取URL中的参数，尝试多种方式
        // 方式1：从普通URL查询参数获取
        const urlParams = new URLSearchParams(window.location.search)
        orderNo.value = urlParams.get('out_trade_no')
        
        // 方式2：如果方式1没有获取到，从hash部分获取
        if (!orderNo.value && window.location.hash.includes('?')) {
            const hashParams = new URLSearchParams(window.location.hash.split('?')[1])
            orderNo.value = hashParams.get('out_trade_no')
        }
        
        // 方式3：直接从本地存储中获取最近的订单号
        if (!orderNo.value) {
            orderNo.value = localStorage.getItem('lastPaymentOrderNo')
        }
        
        // 检查是否有orderNo参数
        if (!orderNo.value) {
            console.error('无法从URL或本地存储中获取订单号，URL:', window.location.href)
            ElMessage.error('订单信息不完整，无法获取订单号')
            loading.value = false
            return
        }
        
        console.log('获取到订单号:', orderNo.value)
    }
    
    try {
        const response = await paymentService.getPaymentStatus(orderNo.value)
        order.value = response.data
        paymentSuccess.value = order.value.status === 1
        
        // 如果支付成功，立即显示成功状态
        if (paymentSuccess.value) {
            console.log('订单已支付成功')
            isProcessing.value = false // 停止显示处理中状态
            clearPollingTimer()
            if (!isPolling) {
                loading.value = false
            }
            return
        }
        
        // 更新处理进度
        if (isPolling) {
            processingProgress.value = Math.min(90, (pollingCount.value / MAX_POLLING_COUNT) * 100)
        }
        
        // 如果支付未成功，尝试手动更新状态
        console.log(`订单状态检查 #${pollingCount.value + 1}: 状态=${order.value.status}，尝试更新状态`)
        await tryManualUpdate()
        
        // 手动更新后再次检查状态
        if (paymentSuccess.value) {
            console.log('手动更新成功，订单状态已更新为支付成功')
            isProcessing.value = false // 停止显示处理中状态
            processingProgress.value = 100
            clearPollingTimer()
        }
        // 如果支付未成功且未达到最大轮询次数，继续轮询
        else if (pollingCount.value < MAX_POLLING_COUNT) {
            pollingCount.value++
            console.log(`准备进行第${pollingCount.value + 1}次状态检查，${POLLING_INTERVAL/1000}秒后执行`)
            
            // 清除之前的计时器（如果有）
            if (pollingTimer.value) {
                clearTimeout(pollingTimer.value)
            }
            
            // 设置新的计时器
            pollingTimer.value = setTimeout(() => {
                checkPaymentResult(true)
            }, POLLING_INTERVAL)
        } else {
            console.log(`达到最大轮询次数(${MAX_POLLING_COUNT})，停止轮询。最终订单状态=${order.value.status}`)
            // 最后一次尝试更新
            await tryManualUpdate()
            
            // 无论结果如何，显示最终状态
            isProcessing.value = false
            processingProgress.value = 100
        }
    } catch (e) {
        console.error('获取支付结果失败:', e)
        ElMessage.error(e.response?.data?.message || '获取支付结果失败')
        // 出错时也停止处理状态显示
        isProcessing.value = false
    } finally {
        if (!isPolling) {
            loading.value = false
        }
    }
}

// 尝试手动更新订单状态
const tryManualUpdate = async () => {
    try {
        console.log('尝试手动更新订单状态:', orderNo.value)
        const response = await paymentService.manualUpdatePaymentStatus(orderNo.value)
        console.log('手动更新订单状态响应:', response)
        
        // 更新成功后，重新获取订单状态
        if (response.code === 200) {
            console.log('手动更新API调用成功，重新获取订单状态')
            const statusResponse = await paymentService.getPaymentStatus(orderNo.value)
            order.value = statusResponse.data
            paymentSuccess.value = order.value.status === 1
            
            if (paymentSuccess.value) {
                console.log('订单状态已成功更新为支付成功')
                // 停止轮询
                clearPollingTimer()
            } else {
                console.log('订单状态仍不是支付成功:', order.value.status)
            }
        }
    } catch (e) {
        console.error('手动更新订单状态失败:', e)
    }
}

// 清理组件时清除计时器
const clearPollingTimer = () => {
    if (pollingTimer.value) {
        clearTimeout(pollingTimer.value)
        pollingTimer.value = null
    }
}

onMounted(() => {
    checkPaymentResult()
})

// 组件卸载时清除计时器
onUnmounted(() => {
    clearPollingTimer()
})
</script>

<style scoped>
.payment-result {
    padding: 20px;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.loading-container {
    padding: 20px;
}

.result-container {
    padding: 20px 0;
}

.order-details {
    max-width: 600px;
    margin: 20px auto 0;
}

.processing-container {
    text-align: center;
    padding: 20px 0;
}

.processing-indicator {
    margin: 20px auto;
}
</style> 